from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from app.config import load_config

config = load_config(".env")


async def create_db_session(config: config):
    engine = create_async_engine(make_connection_string(config), future=True, connect_args={"connect_timeout": 120})

    async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

    return async_session


def make_connection_string(config: config, async_fallback: bool = False) -> str:
    conn_str = (
        f"mysql+aiomysql://{config.db.user}:{config.db.password}@{config.db.host}:"
        f"{config.db.port}/{config.db.database}"
    )
    if async_fallback:
        conn_str += "?async_fallback=True"

    return conn_str
